package com.lincoln.cloud.servercenter.bean;

import com.lincoln.cloud.common.utils.ScannerUtil;
import com.lincoln.cloud.servercenter.annotation.MessageVerify;
import com.lincoln.cloud.servercenter.interfaces.ServerPool;
import com.lincoln.cloud.servercenter.interfaces.Verify;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务注册中心启动代码层面相关配置,与Context分离开
 *
 * @author lincoln
 */
@Data
public class ServerCenterBean {
    /**
     * 扫描路径
     */
    private String[] scannerPath;

    /**
     * 连接池
     */
    private ServerPool serverPool;

    /**
     * 消息校验规则
     */
    private List<Verify> verifies;

    /**
     * 初始化
     */
    public ServerCenterBean() {
        verifies = new ArrayList<>();
        List<Class> classes = ScannerUtil.scan("com.lincoln.cloud.servercenter.protocol", MessageVerify.class);
        if(scannerPath !=null){
            for (String path : scannerPath) {
                classes.addAll(ScannerUtil.scan(path, MessageVerify.class));
            }
        }
        Map<Class, Integer> classIntegerMap = new HashMap<>();
        for (Class clazz : classes) {
            if (Verify.class.equals(clazz.getSuperclass())) {
                try {
                    classIntegerMap.put(clazz, ((MessageVerify) clazz.getAnnotation(MessageVerify.class)).value());
                    verifies.add((Verify) clazz.newInstance());
                } catch (Exception e) {

                }
            }
        }
        verifies.sort((o1, o2) -> {
            if (classIntegerMap.get(o1.getClass()) < classIntegerMap.get(o2.getClass())) {
                return -1;
            } else if (classIntegerMap.get(o1.getClass()).intValue() == classIntegerMap.get(o2.getClass()).intValue()) {
                return 0;
            } else {
                return 1;
            }
        });
    }
}
